package com.sf.algo.http;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {

	/**
	 * 对象转JSON
	 * @param model
	 * @return
	 */
	public static String toJSON(Object model){
		ObjectMapper mapper = new ObjectMapper();
		String json = null;
		try {
			json = mapper.writeValueAsString(model);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}
	
	/**
	 * JSON转对象
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T toObject(String json, Class<T> clazz){
		ObjectMapper mapper = new ObjectMapper();
		T model = null;
		try {
			model = mapper.readValue(json, clazz);
		} catch(Exception e){
			e.printStackTrace();
		}
		return model;
	}
	
	/**
	 * JSON转集合
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> List<T> toList(String json, Class<T> clazz){
		ObjectMapper mapper = new ObjectMapper();
		JavaType javaType = mapper.getTypeFactory().constructCollectionType(List.class, clazz);
		List<T> rows = null;
		try {
			rows = mapper.readValue(json, javaType);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rows;
	}
	
	/**
	 * JSON转数组
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T[] toArray(String json, Class<T> clazz){
		ObjectMapper mapper = new ObjectMapper();
		JavaType javaType = mapper.getTypeFactory().constructArrayType(clazz);
		T[] array = null;
		try {
			array = mapper.readValue(json, javaType);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return array;
	}
	
}